package com.zzh.interview.filter;

import cn.dev33.satoken.stp.StpUtil;
import com.google.gson.Gson;
import com.zzh.interview.common.BaseResponse;
import com.zzh.interview.common.ResultUtils;
import com.zzh.interview.utils.BlackIpUtils;
import com.zzh.interview.utils.NetUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.zzh.interview.common.ErrorCode.LOGIN_CONFLICT;
import static com.zzh.interview.constant.RedisConstant.USER_LOGIN_CONFLICT_TOKEN_KEY;

//登录token冲突拦截器 servlet原生 filter 优先级高于 springmvc 拦截器 优先级高于 springboot 拦截器
@WebFilter(urlPatterns = "/*", filterName = "loginTokenConflictFilter")
@Slf4j
@Order(2)// 数字越小优先级越高
public class LoginTokenConflictFilter implements Filter {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    final Gson gson = new Gson();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取当前token的信息
        String tokenValue = StpUtil.getTokenValue();
        log.info("当前请求token为：{}", tokenValue);
        //检查当前token是不是登录冲突被顶下线的
        Boolean isConflict = redisTemplate.opsForSet().isMember(USER_LOGIN_CONFLICT_TOKEN_KEY, tokenValue);
        if (isConflict) {
            log.info("当前token为登录冲突被顶下线的token，禁止访问");
            // 获取 Token 的名称
            String tokenName = StpUtil.getTokenName();//配置文件中的mianshikaola
            tokenName = String.format("%s:%s:%s", tokenName,"login:token",tokenValue);
            log.info("当前token的名称为：{}", tokenName);
            //同时去除当前token的登录冲突记录
            redisTemplate.opsForSet().remove(USER_LOGIN_CONFLICT_TOKEN_KEY, tokenValue);
            redisTemplate.delete(tokenName);
            // 设置允许跨域的源
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:5173");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
            // 允许携带凭证（如果需要）
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setContentType("text/json;charset=UTF-8");

            BaseResponse conflictResponse = ResultUtils.error(LOGIN_CONFLICT);// 40800 登录冲突
            String json = gson.toJson(conflictResponse);
            response.getWriter().write(json);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
